package com.nine.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nine.common.pojo.Role;
import com.nine.common.pojo.UserRole;
import com.nine.system.dao.RoleDao;
import com.nine.system.dao.UserRoleDao;
import com.nine.system.service.RoleService;
import com.nine.system.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: nine-education-parent
 * @author: ♥丁新华
 * @create: 2023-05-25 00:10
 **/
@Service
public class RoleServiceImpl implements RoleService {

    //注入role
    @Autowired
    private RoleDao roleDao;
    //注入userRole
    @Autowired
    private UserRoleDao userRoleDao;

    /**
     * 查 询 全 部
     * @return
     */
    @Override
    public List<Role> findAll() {
        return roleDao.selectList (null);
    }

    /**
     * 查 询 角 色 ID
     * @param userId
     * @return
     */
    @Override
    public List<Role> findByUserID(String userId) {

        List<Role> aclRoles = roleDao.selectByUserId (userId);

        return aclRoles;
    }

    /***
     * 确 认
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public Integer confirm(String userId, String[] roleIds) {
        //删除该用户具有的角色
        roleDao.deleteByUserId(userId);

        //批量添加用户角色
        List<UserRole> userRoleList = Arrays.stream(roleIds).map(roleId -> new UserRole (IdUtil.getSnowflakeNextId()+"", roleId, userId, 0, LocalDateTime.now(), LocalDateTime.now())).collect(Collectors.toList());
        userRoleDao.insertBatch (userRoleList);
        return null;
    }

    @Override
    public Page<Role> roleList(Integer current, Integer pageSize, RoleVo roleVo) {
        Page<Role> page = new Page<> (current, pageSize);

        QueryWrapper<Role> wrapper = new QueryWrapper<> ();

        //判断一下  模糊查询
        if (StringUtils.hasText (roleVo.getName ())){
            wrapper.like ("role_name",roleVo.getName ());
        }
        if (roleVo.getStatus () == null){
            wrapper.eq ("is_deleted",roleVo.getStatus ());
        }

        Page<Role> userPage = roleDao.selectPage (page, wrapper);

        return userPage;
    }
}
